let sub2Data = JSON.parse(localStorage.getItem('sub2Data')); // 存储人文景观数据的数组

// 初始化表格
function initTable() {
    const tbody = document.querySelector('#landscapeTable tbody');
    tbody.innerHTML = ''; // 清空现有内容

    sub2Data.forEach((item, index) => {
        const row = document.createElement('tr');

        row.innerHTML = `
      <td>${index + 1}</td>
      <td>${item.title}</td>
      <td>${item.desc}</td>
      <td><img src="${item.img}" alt="${item.title}" style="max-width: 100px;" /></td>
      <td>
        <button class="btn" onclick="editSub2Data(${index})">编辑</button>
        <button class="btn" onclick="deleteSub2Data(${index})">删除</button>
      </td>
    `;

        tbody.appendChild(row);
    });
}

// 清空表单
function clearForm() {
    document.getElementById('newTitle').value = '';
    document.getElementById('newDesc').value = '';
    document.getElementById('newImage').value = '';
}

// 存储人文景观数据到 localStorage
function saveToLocalStorage() {
    localStorage.setItem('sub2Data', JSON.stringify(sub2Data));
}

// 从 localStorage 加载人文景观数据
function loadFromLocalStorage() {
    const savedLandscapes = localStorage.getItem('sub2Data');
    if (savedLandscapes) {
        sub2Data = JSON.parse(savedLandscapes);
    }
}

// 初始化表格时加载数据
document.addEventListener('DOMContentLoaded', function () {
    loadFromLocalStorage();
    initTable();
});

// 添加新人文景观后保存数据
function addLandscape() {
    const title = document.getElementById('newTitle').value;
    const desc = document.getElementById('newDesc').value;
    const imgInput = document.getElementById('newImage');
    let imgSrc = './default.jpg'; // 默认图片路径

    if (imgInput.files.length > 0) {
        const file = imgInput.files[0];
        imgSrc = URL.createObjectURL(file); // 创建临时URL
    }

    const newLandscape = { title, desc, img: imgSrc };
    sub2Data.push(newLandscape);

    initTable(); // 更新表格显示
    clearForm(); // 清空表单
    saveToLocalStorage(); // 保存数据
}

// 删除人文景观后保存数据
function deleteSub2Data(index) {
    const landscape = sub2Data[index];

    // 移除旧的临时URL（如果存在）
    if (landscape.img.startsWith('blob:')) {
        URL.revokeObjectURL(landscape.img);
    }

    sub2Data.splice(index, 1);
    initTable(); // 更新表格显示
    saveToLocalStorage(); // 保存数据
}

// 编辑人文景观后保存数据
function editSub2Data(index) {
    const landscape = sub2Data[index];
    document.getElementById('newTitle').value = landscape.title;
    document.getElementById('newDesc').value = landscape.desc;

    // 移除旧的临时URL（如果存在）
    if (landscape.img.startsWith('blob:')) {
        URL.revokeObjectURL(landscape.img);
    }

    sub2Data.splice(index, 1); // 删除旧记录
    initTable(); // 更新表格显示
    saveToLocalStorage(); // 保存数据
}
